<?php
/**
 * User
 *
 * PHP version 5
 *
 * @category Controller
 * @version  1.0
 * @author   Duonght <hduongdmit@gmail.com>
 */
App::uses('AppController', 'Controller');
class MenusController extends AppController {

	/**
	* Components
	* @var array
	*/
	public $components = array('Paginator');
	public $uses = array('Menus');
	private $menu_multi = array();
	private $stt = -1;

	public function beforeFilter(){
		parent::beforeFilter();
		$target = Configure::read('target');
		$this->set('target', $target);
	}

	public function index(){
		$changeBgTr = 'onMouseOver="this.style.background=\''. ConstAdminComponent::BACKGROUND_MOUSEOVER .'\'" onMouseOut="this.style.background=\''. ConstAdminComponent::BACKGROUND_MOUSEOUT .'\'"';
		//get param filter
		$conditions = array('del_flg' => 0);
		if ($this->request->query) {
			$mnu_type = $this->request->query['mnu_type'];
			if(!empty($mnu_type)){
				$conditions['mnu_type'] = $mnu_type;
			}
		}

		$paginate = array(
				'fields' => 'id, mnu_name, mnu_target, mnu_link, mnu_order, mnu_active, mnu_parent_id, mnu_has_child, mnu_level',
				'limit' => ConstAdminComponent::PAGE_NUMBER_LIMIT,
				'conditions' => $conditions,
				'order' => array(
						'mnu_parent_id' => 'asc',
						'mnu_order' => 'asc',
				),
		);

		$this->Paginator->settings = $paginate;
		$listMenu = $this->Paginator->paginate('Menus');

		$menu_level = array();
		foreach ($listMenu as $key => $menu){
			$menus = $menu['Menus'];
			$menu_level[$menus['mnu_parent_id']][$menus['id']] = $menus;
		}

		$this->_sortLevel($menu_level);
		$this->set(array(
				'datas' => $this->menu_multi,
				'changeBgTr' => $changeBgTr,
		));

		$this->set('page_number_limit', ConstAdminComponent::PAGE_NUMBER_LIMIT);
		$this->set('title_for_layout',__('Menus'));
	}

	/**
	 * Add new menu
	 */
	public function add(){
		//get menu parent
		$listMenu = $this->Menus->getListMenu();
		$menu_level = array();
		foreach ($listMenu as $key => $menu){
			$menus = $menu['menus_multi'];
			$menu_level[$menus['mnu_parent_id']][$menus['id']] = $menus;
		}

		$this->_sortLevel($menu_level);
		//set view
		$this->set('list_menu', $this->menu_multi);

		if ($this->request->is('post')) {
			$params = $this->request->data;
			$this->Menus->create();
			$mnu_level = $this->Menus->getLevelMenuParent($params['Menus']['mnu_parent_id']);
			$params['Menus']['mnu_level'] = $mnu_level + 1;

			if ($this->Menus->save($params)) {
				$this->Session->setFlash(__('Success'),'success');
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('Save could not be saved. Please, try again'), 'error');
			}
		}

		//forge view
		$this->set('title_for_layout',__('Add news menu'));
	}

	/**
	 * Edit menus
	 *
	 * @param string $id
	 */
	public function edit($id = null){
		if (!$id) {
			throw new NotFoundException(__('Invalid post'));
		}

		//get detail
		$detail = $this->Menus->findById($id);
		if (!$detail) {
			throw new NotFoundException(__('Invalid post'));
		}

		//get category parent
		$listCategory = $this->Menus->getListMenu();
		$menu_level = array();
		foreach ($listCategory as $key => $category){
			$categorys = $category['menus_multi'];
			$menu_level[$categorys['mnu_parent_id']][$categorys['id']] = $categorys;
		}

		$this->_sortLevel($menu_level);

		//set view
		$this->set('detail', $detail);
		$this->set('list_menu', $this->menu_multi);
		//edit
		if ($this->request->is('post')) {
			$params = $this->request->data;
			$this->Menus->id = $id;
			if ($this->Menus->save($params)) {
				$this->Session->setFlash(__('Updated success.'));
				// $log = $this->Category->getDataSource()->getLog(false, false);
				// debug($log);
				// die;
				return $this->redirect(array('action' => 'index'));
			}

		}
		$this->set('title_for_layout',__('Edit Menu'));
	}

	/**
	 * Update news
	 * @param string $id
	 * @param string $type
	 */
	public function update($id = null, $field = 'active'){
		$this->layout = null;
		$this->render(false);
		if ($this->request->is('post')) {
			$value = $this->request->data['value'];
			$this->Menus->set('id', $id);
			$this->Menus->set($field, $value);
			$this->Menus->save();
			echo $value;
		}
	}

	/**
	 * Delete category
	 *
	 * @param string $id
	 */
	public function delete($id = null){
		$this->layout = null;
		if ($this->request->is('get')) {
			throw new MethodNotAllowedException();
		}

		$this->Menus->read('id', $id);
		$this->Menus->set('mnu_active', 0);
		$this->Menus->save();
		$this->Session->setFlash(__('Delete success'),'success');
		return $this->redirect(array('action' => 'index'));

	}

	/**
	 * Sap xep danh muc theo level
	 *
	 * @param array $arrayCategory
	 * @param number $keystart nút cha
	 * @param number $level
	 */
	private function _sortLevel($arrayCategory, $keystart = 0, $level = -1){
		//kiểm tra xem tồn tại record không
		if (array_key_exists($keystart, $arrayCategory)) {
			$level++;
			foreach ($arrayCategory[$keystart] as $key => $value){

				//gán các phần tử cho array menu sắp xếp theo đúng vị trí
				//tang so thu tu
				$this->stt++;
				$this->menu_multi[$this->stt] = $value;

				//gan level cho menu
				$this->menu_multi[$this->stt]['level'] = $level;

				//thiet lap de biet day la` 1 nut cha
				if (array_key_exists($key,$arrayCategory)){
					$this->menu_multi[$this->stt]["parent"] = 1;
				} else {
					$this->menu_multi[$this->stt]["parent"] = 0;
				}

				//de quy de lap lai, neu menu_id nam trong array cac menu cha
				$this->_sortLevel($arrayCategory, $key, $level);
			}
		}
	}

}
